package com.qf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping("/upload1")
    @ResponseBody
    public String upload1(MultipartFile file1, MultipartFile file2, HttpServletRequest req) throws IOException {

        //文件上传，一定要解决文件重名问题(生成一个唯一文件名)
        /*
            时间：考虑时间回拨问题（时间重置）
            UUID: 可以
         */
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String originalFilename = file1.getOriginalFilename(); //1.a.jpg
        int idx = originalFilename.lastIndexOf('.');//查找上传文件名中最后一个点
        String fileFux = originalFilename.substring(idx); //.jpg
        String fileName = uuid+fileFux;
        System.out.println(fileName);

        //文件往哪存
        String realPath = req.getServletContext().getRealPath("/upload"); //目录

        File destFile = new File(realPath,fileName);

        file1.transferTo(destFile);

        return "上传成功~~";
    }
}
